<template>
	<view class="page-container">
		<use-navbar ref="navbar" type="custom" :show="true" :back="true" :bg-color="navbarBgcolor">
			<template v-slot:title>
				<view class="tac">
					<text class="ft-dark-3 fs-30">{{baseFormInfo.title}}</text>
				</view>
			</template>
		</use-navbar>
		
		<view class="panel padding-sm" style="position: relative;z-index: 99;">
			<view style="height: 65vh;"></view>
			<template v-if="showCustomers">
				<view class="customer dflex-s padding-sm bg-main border-radius">
					<view class="headimg big border-radius-sm dflex-c" @click="addMember('radio','选择宝宝','customer')">
						<text class="iconfont icon-tianjia1 fs-45 fwbd" style="line-height: 32.5px;"></text>
					</view>
					<view class="dflex-bs" style="flex-grow: 1;">
						<view class="padding-left-sm" style="flex-grow: 0.85;">
							<view>
								<text class="padding-lr-xs fs-30">{{baseFormInfo.title}}</text>
								<text class="iconfont icon-bianji fs-40" @click="toEdit('title', '标题', 45,false)"
									style="height: 21px;line-height: 21px;"></text>
							</view>
							<view class="dflex">
								<view class="progress-box flex1">
									<progress :percent="0" stroke-width="6" />
								</view>
								<view class="padding-lr-sm">
									<text class="ft-dark-3">0/0</text>
								</view>
							</view>
							<view class="padding-tb-xs">
								<view class="padding-lr-xs  dflex-sc" @click="gotoPeriod" style="line-height: 1;">
									<text class="iconfont icon-shizhong2" style="color: #2b8aa7;"></text>
									<text class="padding-lr-xxs fs-25">---</text>
									<text class="iconfont icon-xiangyoujiantou"></text>
								</view>
								<view class="bg-gray-2  padding-lr-xs border-radius-xs">
									<text class="fs-20 ft-dark-3" style="line-height: 1;"> </text>
								</view>
							</view>
						</view>
						<view class="dflex dflex-flow-c " style="opacity: 0.35;">
							<image src="../../static/icons/icon-trophy.png" style="width: 35px;" mode="widthFix">
							</image>
							<text class="fwb">+0</text>
						</view>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="customer dflex-s padding-sm bg-main border-radius"
					v-for="(item,idx) in baseFormInfo.customers">
					<view class="headimg big border-radius-sm">
						<image :src="item.avatarUrl" class=" avatar"></image>
					</view>
					<view class="dflex-bs" style="flex-grow: 1;">
						<view class="padding-left-sm">
							<view>
								<text class="padding-lr-xs fs-30">{{baseFormInfo.title}}</text>
								<text class="iconfont icon-bianji fs-40" @click="toEdit('title', '标题', 45,false)"
									style="height: 21px;line-height: 21px;"></text>
							</view>
							<view class="dflex">
								<view class="progress-box flex1">
									<progress :percent="50" stroke-width="6" />
								</view>
								<view class="padding-lr-xs">
									<text>35/90</text>
								</view>
							</view>
							<view class="padding-tb-xs">
								<view class="padding-lr-xs  dflex-sc" @click="gotoPeriod" style="line-height: 1;">
									<text class="iconfont icon-shizhong2" style="color: #2b8aa7;"></text>
									<text class="padding-lr-xxs fs-25">2023年7月24日 16：00</text>
									<text class="iconfont icon-xiangyoujiantou"></text>
								</view>
								<view class="bg-gray-2  padding-lr-xs border-radius-xs">
									<text class="fs-20 ft-dark-3" style="line-height: 1;"> 注：下次课上有比赛，记得带...</text>
								</view>
							</view>
						</view>
						<view class="dflex dflex-flow-c ">
							<image src="../../static/icons/icon-trophy.png" style="width: 35px;" mode="widthFix">
							</image>
							<text class="fwb">+34</text>
						</view>
					</view>
				</view>
			</template>
			<view style="height: 15rpx;"></view>
			<view class="padding-sm bg-main border-radius">
				<uni-forms ref="valiForm" :model="baseFormInfo" labelWidth="75px">
					<uni-forms-item label="服务次数">
						<view class="dflex">
							<view style="width: 95px;" class="padding-lr-sm">
								<uni-easyinput v-model="baseFormInfo.current" @blur="updateForm($event,'title')"
									maxlength="60" :inputBorder="false" placeholder="当前次" />
							</view>
							<text class="fs-25 ft-dark-3">/</text>
							<view style="width: 95px;" class="padding-lr-sm">
								<uni-easyinput v-model="baseFormInfo.total" @blur="updateForm($event,'title')"
									disabled="" axlength="60" :inputBorder="false" placeholder="总次数" />
							</view>
							<text class="fs-23 ft-dark-3">次</text>
						</view>
					</uni-forms-item>

					<uni-forms-item label="余额" name="amount">
						<view class="dflex" style="width: 105px;">
							<view class="padding-right-sm">
								<uni-easyinput v-model="baseFormInfo.amount" type="digit" :inputBorder="false"
									placeholder="请填写" disabled="" />
							</view>
							<text class="fs-23 ft-dark-3">元</text>
						</view>
					</uni-forms-item>
					<uni-forms-item label="老师" name="" :custom="true">
						<view class="cont dflex  member-area">
							<view class="dflex-sc" style="flex-wrap: nowrap;">
								<view class="member-box" v-for="(item, index) in baseFormInfo.teachers" :key="index">
									<view class="dflex-s  dflex-flow-c" v-if="index<3">
										<view class="dflex-s padding-right-sm">
											<view class="headimg border-radius-xs">
												<image :src="item.avatarUrl" class="headimg"></image>
											</view>
											<view class="  tal padding-left-sm" style="min-width: 65px;">
												<view class="dflex-s dflex-flow-c">
													<text class="fs-26 fwbd clamp"
														style="text-wrap: nowrap;">{{ item.markName }}</text>
													<text class="fs-20 clamp ft-dark-3"
														style="text-wrap: nowrap;line-height: 1;">{{ item.mobile||'未设置' }}</text>
												</view>
											</view>
										</view>
										<template v-if="item.tel">
											<view class="dflex fs-23 ft-dark-4 padding-top-xs">
												<text>{{item.tel}}</text>
												<view class="padding-lr-xs">
													<text class="iconfont icon-dianhua"></text>
													<text style="color: #2b8aa7;">拨打</text>
												</view>
											</view>
										</template>
									</view>
								</view>
								<view v-if="baseFormInfo.teachers.length>2">
									<uni-icons type="more-filled" color="#5e6d82" size="22" />
								</view>
							</view>
							<!-- 操作权限 -->
							<view class="item margin-lr-xs padding-tb-xs" @click="addMember('radio','选择老师','teacher')">
								<view class="headimg pos-r tac border-radius-sm border-dashed"
									style="line-height: 1.25;">
									<!-- <uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="plusempty" /> -->
									<text class="iconfont icon-tianjia1 fs-45 fwbd" style="line-height: 42.5px;"></text>
								</view>
							</view>
							<template v-if="baseFormInfo.teachers.length>0">
								<view class="item margin-lr-xs padding-tb-xs" @click="removeMember('teacher')">
									<view class="headimg pos-r tac border-radius-sm border-dashed"
										style="line-height: 1.25;">
										<!-- <uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="minus" /> -->
										<text class="iconfont icon-jianshao fs-45 fwbd"
											style="line-height: 42.5px;"></text>
									</view>
								</view>
							</template>
						</view>
					</uni-forms-item>
					<uni-forms-item label="服务日历" :note="periodText" name="period" :custom="true">
						<view class="padding-lr-xs padding-tb-xs dflex-sc" style="line-height: 1;" @click="gotoPeriod"
							v-for="(item,idx) in baseFormInfo.periods">
							<text class="iconfont icon-shizhong2" style="color: #2b8aa7;"></text>
							<text class="padding-lr-xxs fs-25 ft-dark-4">{{item}}</text>
							<text class="iconfont icon-xiangyoujiantou"></text>
						</view>
						<view class="bg-gray-2  padding-lr-xs border-radius-xs">
							<text class="fs-20 ft-dark-3" style="line-height: 1;"> 注：{{baseFormInfo.nexttips}}</text>
						</view>
					</uni-forms-item>
				</uni-forms>
			</view>

			<view style="height: 15rpx;"></view>
			<view class="bg-main border-radius">
				<uni-collapse>
					<uni-collapse-item title="更多" :show-animation="true">
						<view class="content padding-lr-lg padding-bottom-xs">
							<uni-forms ref="valiForm" :model="baseFormInfo" labelWidth="75px">
								<uni-forms-item label="购买时间">
									<uni-datetime-picker type="date" placeholder="日期（选填）" :border="false"
										:disabled="disabled" v-model="baseFormInfo.buydate"
										@change="bindDateChange($event,'signdate')" />
								</uni-forms-item>
								<uni-forms-item label="起始日期">
									<uni-datetime-picker type="date" placeholder="日期（选填）" :border="false"
										:disabled="disabled" v-model="baseFormInfo.start"
										@change="bindDateChange($event,'signdate')" />
								</uni-forms-item>
								<uni-forms-item label="截止日期">
									<uni-datetime-picker type="date" placeholder="日期（选填）" :border="false"
										:disabled="disabled" v-model="baseFormInfo.end"
										@change="bindDateChange($event,'signdate')" />
								</uni-forms-item>
								<uni-forms-item label="家庭可见" name="age" :custom="true">
									<view class="dflex-sc" @click="visibleChange">
										<text style="line-height: 32.5px;"
											class="ft-dark-3 padding-right-sm">全员可见</text>
										<text class="iconfont icon-bianji fs-40"></text>
									</view>
									<view class="dflex  member-area small">
										<view class="dflex-sc" style="flex-wrap: wrap;">
											<view class="member-box dflex "
												v-for="(item, index) in baseFormInfo.members" :key="index">
												<view class="dflex-bs margin-lr-xxs margin-bottom-sm">
													<view class="headimg  pos-r " style="overflow: visible;">
														<template v-if="showRemove">
															<view class="pos-a wh-full"
																@click.stop="delMember(item,index)" style="z-index:92;">
																<uni-icons class="tag pos-a right top" type="minus"
																	color="#f30000" size="22" />
															</view>
														</template>
														<image :src="item.avatarUrl"
															class="avatar border-radius-lg border-dashed2"></image>
													</view>
												</view>
											</view>
											<!-- 操作权限 -->
											<template v-if="editVisible">
												<view class="item margin-lr-xs padding-tb-xs margin-bottom-sm"
													@click="addAdminMember()">
													<view class="headimg pos-r tac border-radius-sm border-dashed">
														<text class="iconfont icon-tianjia1 fs-35 fwbd"
															style="line-height: 32.5px;"></text>
													</view>
												</view>
												<view class="item margin-lr-xs padding-tb-xs margin-bottom-sm"
													@click="removeMember('member')">
													<view class="headimg pos-r tac border-radius-sm border-dashed">
														<text class="iconfont icon-jianshao fs-35 fwbd"
															style="line-height: 32.5px;"></text>
													</view>
												</view>
											</template>

										</view>
									</view>

								</uni-forms-item>
								<uni-forms-item label="商家/机构" name="age" :custom="true">
									<view class="dflex">
										<view style="padding: 0px 5rpx 0px 5rpx;" class="dflex-b flex1">
											<uni-easyinput v-model="baseFormInfo.ORG.name"
												@blur="updateForm($event,'ORG')" maxlength="60" :inputBorder="false"
												placeholder="请填写商家/机构的名称" />
										</view>
									</view>
									<!-- #ifdef MP-WEIXIN || APP -->
									<view class="padding-bottom-xs dflex" style="line-height: 1.25;">
										<view style="width: 65px;;"></view>
										<template v-if="hasLocation">
											<view class="dflex-b flex1 padding-tb-sm">
												<view class="dflex-c" style="color: #2b8aa7;">
													<text
														class="iconfont icon-weizhi-shi fs-35 padding-right-xxs"></text>
													<text class="fs-25 ">{{baseFormInfo.ORG.address||'请选择地址'}}</text>
												</view>
												<view class="dflex" @click="choiceMap">
													<text
														class="iconfont icon-ditudingwei ft-dark-3 fs-40 padding-right-xxs"></text>
													<text class="fs-23">定位</text>
												</view>
											</view>
										</template>
										<template v-else>
											<view class="dblock" style="line-height: 1;">
												<text class="dblock fs-26 ft-dark-4 margin-right-xs"
													style="line-height: 1.25;">定位服务未开启</text>
												<text class="fs-20 ft-dark-3"
													style="line-height: 1.0;">开启后记录打卡位置信息</text>
											</view>
											<view class="dflex padding-left">
												<button class="mini-btn btn gray ft-dark mini" type="" size="mini"
													@click="openSetting('')">开启</button>
											</view>
										</template>
									</view>
									<!-- #endif -->

								</uni-forms-item>

							</uni-forms>
						</view>
					</uni-collapse-item>
				</uni-collapse>
			</view>
			<view class="border-radius margin-top-sm bg-main">
				<view class="padding-lr-sm padding-top-sm dflex-b">
					<text class="ft-dark-3">流水账</text>
					<view class="dflex-bc">
						<text class="iconfont icon-tianjia4" style="line-height: 1;color: #2b8aa7;"></text>
						<text class="fs-23 ft-dark-3 padding-lr-xxs" style="color: #2b8aa7;">增加</text>
					</view>
				</view>
				<view class="stats-area bg-main padding-lr-sm">
					<view class="item dflex-bc" v-for="(item,idx) in billList">
						<view>
							<text>{{item.date}}</text>
							<text class="iconfont  fs-50" :class="item.icon" :style="{'color':item. color}"></text>
							<text class="ft-dark-3">{{item.text}}</text>
						</view>
						<view style="line-height: 1;">
							<image :src="item.avatarUrl" class="headimg border-radius-xs"></image>
						</view>
						<view>
							<text class="fs-23">{{item.status}}</text>
						</view>
					</view>
				</view>

			</view>
		</view>
		<!-- 统一提交 -->
		<template v-if="showOperArea">
			<view style="height: 75px;"></view>
			<view class="oper-area pos-f dflex-c w-full bg-main">
				<view class="btn small warn padding-lr-lg border-radius-lg dflex-c padding-tb-xs" @click="onDelSubmit">
					<text type="primary" class="dblock">
						删除课程
					</text>
				</view>
			</view>
		</template>

		<use-popup :show="editShow" bgclass=" " mode="top" borderRadius="20" @open='openPopup' @close="closePopup('')">
			<view class="edit-area border-radius bg-main pos-r padding-bottom" style="overflow: visible;">
				<view class="pos-a tac" @click="editShow = false"
					style="right: 15rpx;top: 15rpx;height: 25px;width: 25px;line-height: 25px;">
					<uni-icons type="closeempty" size="18" color="#4a4a4a" />
				</view>

				<view class="dflex-b ft-dark fs-xs margin-bottom-sm margin-lr-xs">
					<view>修改{{editTxt}}</view>
					<template if="editMaxLength!=='0'">
						<view>{{editVal.length}}/{{editMaxLength}}</view>
					</template>
				</view>
				<view class="dflex border-radius-sm field" style="padding: 18rpx 16rpx">
					<textarea class="fwb fs-sm" type="text" v-model="editVal" auto-height disable-default-padding
						style="max-height: 160rpx; min-height: 40rpx; height: 40rpx; font: initial;" :focus="editShow"
						confirm-type="done" :show-confirm-bar="false" cursor-spacing="20" placeholder="请输入"
						placeholder-class="fs-sm" :maxlength="editMaxLength" @confirm="editConfirm" />
				</view>

				<view class="bg-base margin-top-xl tac w-full border-radius-lg padding-tb-sm" @click.stop="editConfirm">
					确定
				</view>
			</view>
		</use-popup>

		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff" @change="change">
			<view class="popup-content" style="width: 72.5vw;">
				<view :style="{'height':customBarHeight +'px'}"></view>
				<view class="dflex padding-sm fs">
					<text>参与成员</text>
				</view>
				<view class="member-area  dflex padding-tb-xs padding-lr-sm" style="flex-wrap: wrap;">
					<view class="item margin-lr-sm padding-tb-xs" v-for="(item,index) in memberList" :key="index">
						<view class="headimg pos-r">
							<template v-if="showRemove">
								<view class="pos-a wh-full" @click.stop="delMember(item,index)" style="z-index:92;">
									<uni-icons class="tag pos-a right top" type="minus" color="#f30000" size="22" />
								</view>
							</template>
							<image :src="item.avatarUrl" class=" border-radius-lg avatar"></image>
							<template v-if="item.isCreator">
								<image src="../../static/icons/icon-admin-02.png" class="tag pos-a"></image>
							</template>
						</view>
						<text class="clamp tac fs-20 padding-tb-xs">{{item.nickName}}</text>
					</view>
					<!-- 操作权限控制 -->
					<view class="item margin-lr-sm padding-tb-xs" @click="addMember('checkbox','选择老师','teacher')">
						<view class="headimg pos-r tac border-radius-sm"
							style="border: 1px double #999;line-height: 1.25;">
							<uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="plusempty" />
						</view>
						<text class="clamp tac fs-20 padding-tb-xs">添加</text>
					</view>
					<view class="item margin-lr-sm padding-tb-xs" @click="removeMember('membar')">
						<view class="headimg pos-r tac border-radius-sm"
							style="border: 1px double #999;line-height: 1.25;">
							<uni-icons :size="32" class="uni-icon-wrapper" color="#bbb" type="minus" />
						</view>
						<text class="clamp tac fs-20 padding-tb-xs">移出</text>
					</view>

				</view>
				<template v-if="memberList.length == 0">
					<use-empty tip="暂无数据" btnTip="" height="25vh" />
				</template>
				<view class="drawer-btns dflex-b pos-f w-full safe-area-inset-bottom" style="bottom: 15rpx;">
					<view class="tac padding-tb-xs flex1 bg-gray  margin-xs  border-radius-big" style="width: 42.5%;"
						@click="onClickClose">关闭</view>
					<view class="tac padding-tb-xs flex1  bg-base margin-xs border-radius-big" style="width: 42.5%;"
						@click="shareToggle">
						分享
					</view>
				</view>

			</view>
		</uni-popup>

		<!-- 分享示例 -->
		<uni-popup ref="share" type="share" safeArea backgroundColor="#fff">
			<uni-popup-share></uni-popup-share>
		</uni-popup>
	</view>
</template>

<script setup>
	// 在组件中引入并使用
	import {
		filterIllegalCharacters
	} from '@/utils/validate.js'
	// --组合式 API 模板
	import {
		ref,
		reactive,
		provide,
		onMounted,
		computed,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app";
	import {
		storeToRefs
	} from 'pinia';
	import {
		useUserStore
	} from '@/store'

	const {
		ctx,
		proxy
	} = getCurrentInstance();
	console.log("ctx", ctx);

	let UserStore = useUserStore()
	provide('location', 'North Pole')
	const title = ref("流水账记录")
	const navbarBgcolor = ref('#f1f1f1')
	const pattern = ref({
		color: '#7A7E83',
		backgroundColor: '#fff',
		selectedColor: '#007AFF',
		buttonColor: '#60d1ca',
		iconColor: '#fff'
	})
	const loading = ref(false)
	const inviteShow = ref(true)
	const modeType = ref('checkbox'); // -- 记录单选、多选
	const locked = ref(false); // --记录是否需要锁定人员
	const updateType = ref('radio'); // --更新数据类型
	const type = ref('')
	const active = ref(0);
	const current = ref(0)

	const clipperShow = ref(false)
	const editShow = ref(false)
	const editKey = ref('')
	const editVal = ref('')
	const editTxt = ref('')
	const editMaxLength = ref(30)
	const editVisible = ref(false)
	const showHeadPicker = ref(false)
	const seachText = ref('')
	const datePickerInfo = ref({
		title: '',
		show: false,
		type: '',
		more: {
			type: '',

			data: {
				dm: '',
				state: ''
			}
		}
	})
	const billList = ref([{
		id: '',
		text: '次数 - 1',
		date: ' 2023年7月24日  16：00  ',
		avatarUrl: "https://jydd-anan-shanghai.oss-cn-shanghai.aliyuncs.com/userAvatar/2023-09-26/20230926033914692081_20230926033914692081.png",
		status: '已确认',
		state: ''
	}, {
		id: '',
		text: '次数 - 1',
		date: ' 2023年7月24日  16：00  ',
		avatarUrl: "https://jydd-anan-shanghai.oss-cn-shanghai.aliyuncs.com/userAvatar/2023-09-26/20230926033914692081_20230926033914692081.png",
		status: '已确认',
		state: ''
	}])

	const allMemberList = ref([]) // --成员原始列表 
	const memberList = ref([]) // --弹窗加载展示列表 
	const checkList = ref([])


	// --统一表单
	const _id = ref('')
	const disabled = ref(false); // --记录单据是否可编辑
	const teacherRemove = ref(false)
	const showRemove = ref(false)
	const periodText = ref('')
	const baseFormInfo = ref({
		title: '',
		customers: [],
		teachers: [{
			avatarUrl: "https://jydd-anan-shanghai.oss-cn-shanghai.aliyuncs.com/userAvatar/2023-09-26/20230926033914692081_20230926033914692081.png",
			checked: false,
			nickName: "韩囡囡",
			rid: "803",
			role: "普通用户",
			tag: "members",
			_id: "ce1393bd-469f-4ca1-9afc-4bd7989be773"
		}],
		members: [{
			avatarUrl: "https://jydd-anan-shanghai.oss-cn-shanghai.aliyuncs.com/userAvatar/2023-09-26/20230926033914692081_20230926033914692081.png",
			checked: false,
			isSuperAdmin: false,
			locking: false,
			nickName: "韩囡囡",
			rid: "803",
			role: "普通用户",
			tag: "members",
			_id: "ce1393bd-469f-4ca1-9afc-4bd7989be773"
		}],
		ORG: {
			name: '',
			id: '',
			address: '',
			coordinate: ''
		},
		buydate: '',
		start: '',
		end: '',
		timesleft: '',
		nexttips: '',
		amount: '',
		period: '',
		periods: []
	});
	const contract = ref({
		name: '',
		id: ''
	})
	const hasLocation = ref(true);
	const location = ref({
		address: '',
		coordinate: ''
	})
	const addrData = ref({
		consignee: '',
		mobile: '',
		area: '',
		areaCode: "",
		address: '',
		label: '',
		isDefault: 0,
		addr_source: '录入',
		remark: '家',
		longitude: '',
		latitude: '',
	})
	// onLoad 接受 A 页面传递的参数
	onLoad((option) => {
		console.log("B 页面 onLoad:", option); //B 页面 onLoad: {id: '1', name: 'uniapp'}
		if (option && option.type) {
			title.value = option.type
			type.value = option.type
			uni.setNavigationBarTitle({
				title: option.type
			})
		}

		if (option && option.id) {
			_id.value = option.id
		}
		init();
		uni.$on('__event_choice_member', data => {
			updateMember(updateType.value, data);
		});
	});

	onShow(() => {
		console.log("B 页面 onShow");
	});

	const init = () => {
		if (!_id.value) return;
		loadData('P_SaaS_MCDA_ContentPage', '', (res) => {
			console.log("获取基础数据", res)
			try {
				let _info_ = res.data1[0];
				let _list = [];
				res.data2.forEach((x) => {
					_list.push({
						avatarUrl: x.avatarurl,
						nickName: x.nickname,
						role: x.role,
						unionId: x.unionid,
						user_id: x.user_id,
						markName: x.user_name,
						valid: x.valid
					})
				})
				let _groups = _list.reduce(function(acc, obj) {
					var key = obj.role;
					if (!acc[key]) {
						acc[key] = [];
					}
					acc[key].push(obj);
					return acc;
				}, {});
				console.log(_groups);
				let _periods_ = _info_.periods;
				let _periods = '';
				if (!_info_.periods) {
					_periods = '';
				} else {
					periodText.value = "（" + _periods_.split("|")[0] + "）";
					_periods = _periods_.split("|")[1].split(";");
					console.log(_periods);
				}
				console.log(_groups.customer)
				baseFormInfo.value = {
					title: _info_.name,
					teachers: _groups.server || [],
					members: _groups.user || [],
					customers: _groups.customer || [],
					ORG: {
						name: _info_.serviceorg,
						id: '',
						address: _info_.orgaddress,
						coordinate: _info_.orggis
					},
					timesleft: '',
					nexttips: _info_.nexttips,
					amount: _info_.amount,
					period: _info_.periods,
					periods: _periods || []
				}
				console.log(baseFormInfo.value)
				fmtMemberData(res.data2);
			} catch (e) {
				//TODO handle the exception
				console.log(e)
			}
			uni.hideLoading();
		})

	}

	//  --创建事项,统一提交,删除
	const onSubmit = (e) => {
		console.log('e', e, baseFormInfo.value);
		let requestType = '',
			_ids = [],
			_type = null;
		if (baseFormInfo.value.members != undefined)
			baseFormInfo.value.members.forEach((x) => {
				_ids.push(x._id)
			})
		console.log(_ids)
		let _mode = {};
		let _approver = '';
		if (baseFormInfo.value.hasApproval) {
			if (Object.keys(baseFormInfo.value.approver).length === 0) {
				proxy.$utils.msg('请先选择事项审批人');
				return;
			}
			_approver = baseFormInfo.value.approver.id;
			// --选择完审批人,同步更新到参与成员里
			if (_ids.indexOf(_approver) == -1) {
				_ids.push(baseFormInfo.value.approver.id);
			}
		}
		console.log(baseFormInfo.value);
		let __bool = proxy.$utils.compareDate(baseFormInfo.value.start, baseFormInfo.value.end);
		if (__bool) {
			proxy.$utils.msg('开始日期不能晚于结束日期');
			return;
		}
		_type = "日常";
		requestType = 'P_SaaS_CreateNewDailyAffair';
		_mode = {
			userlist: _ids.join(","),
			approver: _approver
		}
		console.log(baseFormInfo.value, _mode);
		proxy.$refs.valiForm.validate()
			.then((res) => {
				console.log(res)
				proxy.$utils.alert('您确定要创建该事项吗？', function(res) {
					if (res) {
						uni.showLoading({
							title: ''
						})
						loadData(requestType, _mode, (res) => {
							console.log(res);
							uni.hideLoading()
							if (res && res.status == '1') {
								proxy.$utils.msg("创建成功");
								proxy.$utils.timerout(() => {
									uni.redirectTo({
										url: `/sub-matter/pages/detail?id=${res.data1[0].tid}&sticky=0&affairType=${_type}&affairTitle=`
									});
								}, 2150)
								return;
							}
							proxy.$utils.msg("系统错误");
						});
					}
				}, false);
			}).catch((err) => {
				console.log(err)
				proxy.$utils.msg("系统错误");
			})
	}
	//  --创建事项,统一提交,删除
	const onDelSubmit = (e) => {
		proxy.$utils.alert('确定要删除当前课程吗？', function(bool) {
			if (bool) {
				uni.showLoading({})
				loadData('P_SaaS_MCDA_DeleteDA', '', (res) => {
					console.log(res);
					uni.hideLoading()
					if (res && res.status == '1') {
						proxy.$utils.msg(res.data1[0].tips);
						if (res.data1 && res.data1[0].status == '1') {
							proxy.$utils.timerout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 2150)
							return;
						}
						return;
					}
					proxy.$utils.msg("系统错误");
				});
			}
		}, false)

	}

	// --选择完成员后更新相应数据
	const updateMember = (type, data) => {
		console.log(type, data, modeType.value);
		let _mode = {},
			_old_ids = [],
			_new_ids = [];
		switch (modeType.value) {
			case 'teacher':
				console.log("原成员", baseFormInfo.value.teachers, "选择成员数据", data);
				if (!_id.value) {
					baseFormInfo.value.teachers = data;
					return;
				}
				baseFormInfo.value.teachers.forEach((x) => {
					_old_ids.push(x._id);
				})
				data.forEach((x) => {
					_new_ids.push(x._id);
				})
				_mode = {
					new_list: _new_ids.join(','),
					old_list: _old_ids.join(','),
					column: 'server'
				};
				break;
			case 'customer':
				console.log("原成员", baseFormInfo.value.customers, "选择成员数据", data);
				if (!_id.value) {
					baseFormInfo.value.customers = data;
					return;
				}
				baseFormInfo.value.customers.forEach((x) => {
					_old_ids.push(x._id);
				})
				data.forEach((x) => {
					_new_ids.push(x._id);
				})
				_mode = {
					new_list: _new_ids.join(','),
					old_list: _old_ids.join(','),
					column: 'customer'
				};
				break;
			default:
		}
		console.log(_mode);
		updateMemberData(_mode);
	}

	const updateMemberData = (mode) => {

		loadData('P_SaaS_MCDA_Member_Change', mode, (res) => {
			console.log(res)
			try {
				let _res = res.data1[0];
				if (_res.status == '1') {
					proxy.$utils.msg(_res.tips);
					if (_res.status == '1') {
						proxy.$utils.timerout(() => {
							init();
						}, 350)
						return;
					}
					return;
				}
				proxy.$utils.timerout(() => {}, 250)
			} catch (e) {
				//TODO handle the exception
			}
		});
	}
	// --下拉搜索框
	const searchCode = (e) => {

	}

	const switchChange = (e, type) => {
		console.log(e, type)
		baseFormInfo.value.hasApproval = e.detail.value;
		if (!e.detail.value) {
			baseFormInfo.value.approver = {};
		}
	}
	const change = (state) => {
		console.log(state)
	}
	const shareToggle = () => {
		proxy.$refs.share.open()
	}
	const onClickClose = () => {
		proxy.$refs.popup.close()
	}
	const removeMember = (type) => {
		console.log(type)
		switch (type) {
			case 'teacher':
				teacherRemove.value = !teacherRemove.value;
				break;
			case 'member':
				showRemove.value = !showRemove.value;
				break;
			default:
				break;
		}
	}

	const delMember = (item, idx) => {
		console.log(item, idx);
		let _name = item.nickName || '匿名用户';
		proxy.$utils.alert('您确定要移出‘' + _name + '’吗？', function(bool) {
			if (bool) {
				let _mode = {
					id: item._id,
					site: ''
				}
				console.log(_mode)
				loadData('P_Saas_RemoveUser', _mode, (res) => {
					console.log(res)
					try {
						if (res && res.status == '1') {
							proxy.$utils.msg(res.data1[0].tips);
							// --删除后更新成员数据
							proxy.$utils.timerout(() => {
								showRemove.value = false;
								onLoadData();
							}, 350)
							return;
						}
						proxy.$utils.msg("系统错误");
					} catch (e) {
						//TODO handle the exception
					}
				});
			}
		}, false);
	}
	const showMemberPopup = (mode) => {
		updateType.value = mode;
		checkList.value = [];
		let __tit = '',
			__bool = false;
		switch (mode) {
			case 'head':
				//只有主管理员才能点击
				if (UserStore.member.member_rid != '625') return;
				__tit = '更换负责人'
				modeType.value = 'radio';
				checkList.value.push(baseFormInfo.admin.id);
				break;
			case 'member':
				__tit = '选择参与成员'
				modeType.value = 'checkbox';
				memberList.value = baseFormInfo.value.members;
				memberList.value.forEach((x) => {
					x.checked = false;
					checkList.value.push(x._id);
				})
				break;
			default: //--
				console.log('default')
		}
		console.log(checkList.value, baseFormInfo.value);
		if (!_id.value) {
			addMember(modeType.value, __tit);
			return;
		}
		if (baseFormInfo.value.members.length > 0) {
			proxy.$refs.popup.open('right')
		} else {
			addMember(modeType.value, __tit)
		}
	}

	const addMember = (type, title, model) => {
		// --已选成员id,先用url地址栏传值的方式，后期再优化
		modeType.value = model;
		let _ids = []
		checkList.value.forEach((x) => {
			_ids.push(x)
		})
		console.log(_ids);
		uni.navigateTo({
			url: `/pages/member/list?id=${_ids.join(',')}&creater=${UserStore.member.member_id}&type=${type}&title=${title}&locked=${locked.value}&source=1&model=${model}`,
			complete() {}
		});
	}
	const visibleChange = () => {

	}
	const bindDateChange = async (e, type) => {
		console.log(e, type)
		switch (type) {
			case 'task':
				TaskFormInfo.value.end = e.detail.value;
				break;
			case 'offer':
				OfferFormInfo.value.date = e.detail.value;
				break;
			default:
				break;
		}
	}
	const openPopup = (state) => {

	}
	const closePopup = (type) => {
		console.log(type)
		//ctx.$refs.datePopup.close() //--uniapp的弹窗控件
		switch (type) {
			case 'date':
				datePickerInfo.value.show = false
				break;
			case 'customer':
				showCustomerPicker.value = false
				break;
			default:

		}
	}
	const showPopupType = (type) => {
		console.log("弹窗", type, MonthDayList.value)
		switch (type) {
			case 'matter':
				showMatterPicker.value = true;
				if (getMatterState.value) return;
				loadData('P_SaaS_ContractList', '', (res) => {
					console.log(res)
					getMatterState.value = true;
					let list = res.data1
					if (list.length > 0) {
						for (var item of list) {
							if (item.type.length > 0) {
								MatterList.value.push(item);
							}
						}
					}
				})
				//ctx.$refs.datePopup.open('bottom')
				break;

			case 'customer':
				showCustomerPicker.value = true
				break;
			default:

		}
	}
	const gotoPeriod = () => {
		uni.navigateTo({
			url: `/pages/timeslot/serviceTimeSet?id=${_id.value}&periods=${baseFormInfo.value.period}`
		});
	}
	const addAdminMember = () => {
		let _ids = []
		checkList.value.forEach((x) => {
			_ids.push(x)
		})
		console.log(_ids);
		uni.navigateTo({
			url: `/pages/member/list?id=${_ids.join(',')}&creater=${UserStore.member.member_id}&type=checkbox&title=选择家庭成员&locked=${locked.value}&source=1`,
			complete() {}
		});
	}
	const toEdit = (key, txt, len, bool) => {
		console.log(key, txt, len, bool)
		if (bool) return;
		let _val = baseFormInfo.value[key];
		console.log(_val, _val.length)
		editShow.value = true;
		editKey.value = key;
		editTxt.value = txt;
		editVal.value = _val;
		editMaxLength.value = len;
	}
	const editConfirm = () => {
		console.log(editKey.value)
		let data = {};
		data[editKey.value] = editVal.value.replace(/\n/g, '').replace(/\r\n/g, '').trim();
		if (!data[editKey.value]) {
			proxy.$utils.msg('请填写' + editTxt.value);
			return;
		}
		switch (editKey.value) {
			case 'member_nickname':
				memberInfo.value['member_nickname'] = data[editKey.value];
				break;
			case 'member_truename':
				memberInfo.value['member_truename'] = data[editKey.value];
				break;
			case 'email':
				let exg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/;

				if (!exg.test(data[editKey.value])) {
					proxy.$utils.msg('请输入正确的邮箱');
					return;
				}
				memberInfo.value[editKey.value] = data[editKey.value];
				break;
			default:
				memberInfo.value[editKey.value] = data[editKey.value];
		}
		utils.timerout(() => {
			editShow.value = false
		}, 250);
	}

	const fmtMemberData = async (userList) => {
		console.log(userList);
		if (!userList) {
			baseFormInfo.value.customers = [];
			baseFormInfo.value.teachers = [];
			baseFormInfo.value.members = [];
			return;
		}
		// 使用 reduce 方法进行分组
		let groupedData = userList.reduce((result, item) => {
			const group = item.role;
			console.log(group)
			if (!result[group]) {
				result[group] = [];
			}
			result[group].push(item);
			return result;
		}, {});
		console.log(groupedData);
	}
	const updateForm = async (e, key) => {
		console.log(e, key)
		let r = filterIllegalCharacters(e.detail.value);
		console.log("替换后的内容", r);
		baseFormInfo.value[key] = r;
	}
	// 当前登录人权限判断，需做调整？？？
	const checkPermissions = (adminId) => {
		disabled.value = UserStore.member.member_id == adminId ? false : true;
	}
	const loadData = async (type, mode, callback) => {
		let param, _param, _res, __res;
		switch (type) {
			case 'P_SaaS_MCDA_ContentPage':
				param = {
					storedPro: 'P_SaaS_MCDA_ContentPage',
					paraNum: 1,
					resultSetNum: 2,
					para1: _id.value
				}
				_res = await getData(param);
				break;
				// --基础表单信息变更
			case 'P_SaaS_MCDA_ChangeDAInfo':
				param = {
					storedPro: 'P_SaaS_MCDA_ChangeDAInfo',
					paraNum: 4,
					resultSetNum: 1,
					para1: _id.value,
					para2: UserStore.member.member_id,
					para3: mode.column,
					para4: mode.value
				}
				_res = await getData(param);
				break;
				// --表单用户信息变更
			case 'P_SaaS_MCDA_Member_Change':
				param = {
					storedPro: 'P_SaaS_MCDA_Member_Change',
					paraNum: 4,
					resultSetNum: 1,
					para1: _id.value,
					para2: mode.new_list,
					para3: mode.old_list,
					para4: mode.column //--user,server,customer
				}
				_res = await getData(param);
				break;
			case 'P_SaaS_MCDA_DeleteDA': //  --删除流水账
				param = {
					storedPro: 'P_SaaS_MCDA_DeleteDA',
					paraNum: 1,
					resultSetNum: 1,
					para1: _id.value
				}
				_res = await getData(param);
				break;
			case 'P_SaaS_FindAnnualObjectives':
				param = {
					storedPro: 'P_SaaS_FindAnnualObjectives',
					paraNum: 0,
					resultSetNum: 1
				}
				_res = await getData(param)
				break;
			case 'P_SW_CommonUse':
				param = {
					storedPro: 'P_SW_CommonUse',
					paraNum: 1,
					resultSetNum: 1,
					para1: businessType.value.list[businessType.value.current]
				}
				_res = await getData(param)
				break;
			case 'P_SW_Participant':
				param = {
					storedPro: 'P_SW_Participant',
					paraNum: 1,
					resultSetNum: 1,
					para1: ''
				}
				_res = await getData(param)
				break;

			case 'decryptData':
				param = {
					storedPro: 'decryptData',
					paraNum: 1,
					resultSetNum: 1,
					para1: mode
				}
				_res = await getData(param)
				break;

			default:
		}

		if (typeof callback === 'function') {
			// 数据加载完成回调函数
			callback(_res);
		}
	}
	const getData = (param) => {
		let url = proxy.$config.baseUrl;
		let params = {
			loading: false,
			url: '/webapi/eidData.ashx?oper=LTTG_Multifunction',
			method: 'get',
			data: param
		}
		return new Promise((resolve, reject) => {
			proxy.$api.getData(url, params).then((res) => {
				//console.log(res);
				if (res.status == '1') {
					resolve(res);
				} else {
					reject('获取信息失败' + res.msg)
				}
			})
		})
	}
	const getMemberList = () => {
		// --获取成员列表
		return new Promise((resolve, reject) => {
			loadData('P_SaaS_FindUserbyFamily', '', (res) => {
				console.log("获取成员列表", res)
				if (res.status == '1') {
					let datas = []
					res.data1.forEach((x) => {
						datas.push({
							avatarUrl: x.avatarurl,
							_id: x.userid,
							userName: x.user_name,
							nickName: x.user_name,
							rid: x.rid,
							role: x.role,
							checked: false,
							isCreator: false
						})
					})
					console.log(datas)
					UserStore.putMemberList(datas);
					resolve(datas);
				} else {
					reject('获取信息失败' + res.msg)
				}
			})
		})
	}
	// --地图选择
	const choiceMap = (res) => {
		// #ifdef MP-WEIXIN || MP-BAIDU || APP || H5
		choiceMapAddr(res);
		// #endif
	}
	// --选择地图地址
	const choiceMapAddr = (options) => {
		// #ifdef APP
		uni.authorize = (res) => {
			res && res.success();
		};
		// #endif
		uni.authorize({
			scope: 'scope.userLocation',
			success() {
				console.log("地图选择");
				uni.chooseLocation({
					success: res => {
						console.log('位置', res);

						if (res && res.name) {
							let __addr = resolveAddr(res);
							console.log(__addr);
							addrData.value.province_name = __addr.province || '';
							addrData.value.city_name = __addr.city || '';
							addrData.value.area_name = __addr.area || '';
							addrData.value.area = __addr.addr || '';
							addrData.value.address = __addr.addr;
							location.value.address = addrData.value.address;

							addrData.value.longitude = res.longitude + '';
							addrData.value.latitude = res.latitude + '';

							addrData.value.address = res.name;
							// #ifdef APP
							addrData.value.address = res.address.replace(__addr.addr.replace(
								/-/g, ''), '');
							// #endif
						}
					},
					fail(err) {
						console.log(err);
						uni.showModal({
							title: '打开地图失败！' + err,
							success: function(res) {}
						});
					}
				});
			},
			fail(err) {
				console.log("打开地图失败！" + err);
				uni.showModal({
					title: '位置未授权，打开设置',
					success: function(res) {
						if (res.confirm) {
							uni.openSetting({});
						}
					}
				});
			}
		});
	}

	// --解析地址
	const resolveAddr = (options) => {
		let str = options.address;
		let __addr = {
			addr: ''
		};
		let __idx = 0;
		let __idx_pro = str.indexOf('省');

		if (__idx_pro == -1) {
			__idx = str.indexOf('自治区');
			if (__idx != -1) {
				__addr.province = str.substring(0, __idx + 3);
			} else {
				__addr.province = str.substring(0, 0);
				__idx = 0;
			}
		} else {
			__addr.province = str.substring(0, __idx_pro + 1);
		}

		if (__addr.province) __addr.addr += __addr.province + '-';

		let __idx_city = str.indexOf('市');
		if (__idx_city == -1) {
			__idx = str.indexOf('自治州');
			if (__idx != -1) {
				__addr.city = str.substring(__idx_pro + 1, __idx + 3);
			} else {
				__addr.city = str.substring(__idx + 1, __idx_city + 1);
			}
		} else {
			if (__idx == 0) {
				__addr.city = str.substring(__idx_pro + 1, __idx_city + 1);
			} else {
				__addr.city = str.substring(__idx + 3, __idx_city + 1);
			}
		}

		if (__addr.city) __addr.addr += __addr.city + '-';

		let __idx_area = str.lastIndexOf('区');
		if (__idx_area == -1) {
			__idx_area = str.indexOf('县');
			if (__idx == 0) {
				__addr.area = str.substring(__idx_city + 1, __idx_area + 1);
			} else {
				__addr.area = str.substring(__idx + 3, __idx_area + 1);
			}
		} else {
			if (__idx == 0) {
				__addr.area = str.substring(__idx_city + 1, __idx_area + 1);
			} else {
				__addr.area = str.substring(__idx + 3, __idx_area + 1);
			}
		}

		if (__addr.area) __addr.addr += __addr.area;

		return __addr;
	}

	const toBack = (tim) => {
		proxy.$utils.timerout(() => {
			uni.navigateBack({
				delta: 1,
				success: () => {
					// 返回成功后的回调函数				
				},
				fail: () => {
					// 返回失败后的回调函数
				}
			})
		}, tim)
	}

	const showOperArea = computed(() => {
		return true;
	})
	const showCustomers = computed(() => {
		console.log(baseFormInfo.value.customers);
		console.log(baseFormInfo.value.customers.length == 0 ? true : false)
		return baseFormInfo.value.customers.length == 0 ? true : false;
		return !baseFormInfo.value.customers ? true : false;
	})
	const customBarHeight = computed(() => {
		// #ifdef APP-PLUS || MP-WEIXIN
		return UserStore.systemInfo.statusBar + 15
		// #endif
		// #ifdef H5
		return 15
		// #endif
	})
	onMounted(() => {})
</script>

<style lang="scss" scoped>
	page,
	.page-container {
		background-color: $uni-bg-color-grey;
		min-height: 100vh;
	}

	.uni-forms-item {
		margin-bottom: 7.5px;
	}

	.edit-area {
		width: 80vw;
		padding: 100rpx 80rpx 45rpx 80rpx;
		margin-top: 20vh;
		margin-left: 10vw;
		margin-right: 10vw;
		margin-bottom: 5px;

		.field {
			background-color: #f5f5f5;
		}
	}


	// --操作区
	.oper-area {
		left: 0;
		bottom: 0;
		box-shadow: 0 0 20rpx 0 #f0f0f0;
		height: 100rpx;
		height: calc(env(safe-area-inset-bottom) + 100upx);
		z-index: 95;

		.btn-area {
			background: rgba(255, 255, 255, 0.95);

			.btn {
				font-size: 24upx;
				color: 75787d;
			}

			.iconfont {
				font-size: 40rpx;
				line-height: 48rpx;
			}
		}
	}

	.customer {
		.headimg.big {
			width: 65px;
			height: 65px;
			background-color: #f5f5f5;

			.avatar {
				max-width: 100%;
				height: 100%;
			}
		}
	}

	.stats-area {
		.item {
			padding: 5rpx 0 5rpx 0;

			.headimg {
				width: 25px;
				height: 25px;
			}
		}

		.num {
			font-size: 14px;
			color: #3a3a3a;
			margin-bottom: 6rpx;
		}
	}

	.uni-progress-bar {}
</style>